package org.example.testdemo1.service

import com.google.gson.Gson
import okhttp3.OkHttpClient
import okhttp3.Request
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Service
import java.io.IOException

@Service
class WeChatService {

    private val client = OkHttpClient()
    private val gson = Gson()


    @Value("\$ {wechat.appid}")
    lateinit var appId: String

    @Value("\$ {wechat.secret}")
    lateinit var secret: String


    fun getAccessToken(code: String): java.util.HashMap<*, *>? {
        val url = "https://api.weixin.qq.com/sns/jscode2session?appid= $appId&secret=$secret&js_code=$code&grant_type=authorization_code"
        val request = Request.Builder().url(url).build()
        client . newCall (request).execute().use {
            response ->  if (!response.isSuccessful) throw IOException("Unexpected code $ response")
            return gson.fromJson(response.body?.string(), HashMap::class.java)
        }

    }

    fun getUserInfo(accessToken: String, openId: String): java.util.HashMap<*, *>? {
        val url = "https://api.weixin.qq.com/sns/userinfo?access_token= $accessToken&openid=$openId&lang=zh_CN"
        val request = Request.Builder().url(url).build()
        client.newCall(request).execute().use {
            response ->
            if (!response.isSuccessful) throw IOException("Unexpected code  $ response")
            return gson.fromJson(response.body?.string(), HashMap::class.java)
        }
    }
}